import struct
#import matplotlib.pyplot as plt

import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout

import sys

## 解析bin文件，将原始数据规整到各个channel中
class BinDataParser(object):
    def __init__(self, bin_data_path, frame_number, channel_number):
        super().__init__()
        self.bin_data_path = bin_data_path
        self.frame_number = frame_number
        self.channel_number = channel_number
        self.samples_count_per_frame = 0
        self.sample_data = None

    def parseData(self):
        data_file = open(self.bin_data_path, 'rb')
        header_data = data_file.read(8)
        header = struct.unpack('3B5B', header_data)

        b1 = header[2]
        b2 = header[1]
        b3 = header[0]
        length = b1 + b2 * 256 + b3 * 256 * 256
        samples_per_frame = int(length/16)
        self.samples_count_per_frame = samples_per_frame

        self.sample_data = np.zeros(shape = (self.frame_number, self.channel_number, samples_per_frame), dtype = np.int16)

        for frame in range(0, self.frame_number):
            for sample in range(0, samples_per_frame):
                ch = []      # 所有通道一次采样的值
                for j in range(0, int(self.channel_number/4)):
                    line_data = data_file.read(8)       # 1行数据为8个字节
                    chb = struct.unpack('8B', line_data)
                    chb = chb[::-1]
                    for i in range(0, 4):
                        b1 = int(chb[i * 2])
                        b2 = int(chb[i * 2 + 1])
                        if b2 < int(128):
                            sample_value = b1 + b2 * 256
                        else:
                            sample_value = b1 + b2 * 256 - 0x10000    #value可能为负值
                        ch.append(sample_value)

                self.sample_data[frame, :, sample] = ch
                # for channel in range(0, self.channel_number):
                #     self.sample_data[frame, channel, sample] = ch[channel]
            
            header_data = data_file.read(8)  # skip the header of 8 bytes
        
        return self.sample_data

    def getSampleCountPerFrame(self):
        return self.samples_count_per_frame
    
    def getFrameData(self, frame):
        return self.sample_data[frame, :, :]
    
    def getChannelData(self, frame, channel):
        return self.sample_data[frame, channel, :]
    
    def saveData(self):
        pass


if __name__ == '__main__':
    filename = "D:/Project/pabone/data/raw/Rawdata_FPGA1_Frame33.bin"
    # filename="D:/Project/pabone/data/raw/Rawdata_FPGA1_Frame5.bin"
    frame_count = 7
    channel_count = 64

    binDataParser = BinDataParser(filename, frame_count, channel_count)
    pai_acq_data = binDataParser.parseData()
    print(pai_acq_data.shape)

    app = pg.mkQApp("Testing")
    win = pg.GraphicsLayoutWidget(show = True, title = "acq data")
    win.resize(1000,600)
    win.setWindowTitle('pyqtgraph example: Plotting')
    pg.setConfigOptions(antialias=True)
    
    p4 = win.addPlot(title="Parametric, grid enabled")
    x = np.array(range(0, binDataParser.getSampleCountPerFrame()))
    y = pai_acq_data[6, 63, :]
    p4.plot(x, y)
    p4.showGrid(x=True, y=True)
    pg.exec()
